package com.kk.base.service.admin;

import com.kk.base.bean.PageBean;
import com.kk.base.dao.admin.BuyOffDao;
import com.kk.base.dao.home.ExpressMailOrderDao;
import com.kk.base.entity.admin.ProcessRecords;
import com.kk.base.entity.admin.User;
import com.kk.base.entity.admin.BuyOff;
import com.kk.base.entity.common.ExpressMailOrderStatus;
import com.kk.base.entity.home.ExpressMailOrder;
import com.kk.base.util.SendEmailUtil;
import com.kk.base.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.Predicate;
import java.util.List;

@Service
public class BuyOffService {

    @Autowired
    private BuyOffDao buyOffDao;

    @Autowired
    private ExpressMailOrderDao expressMailOrderDao;


    @Value("${email.address}")
    private String sourceEmail; //发件人邮箱

    @Value("${email.authorization-code}")
    private String authorizationCode; //授权码

    /**
     * 分页查询揽收列表
     * @param pageBean
     * @return
     */
    public PageBean<BuyOff> findList(PageBean<BuyOff> pageBean, String waybillNumber) {
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<BuyOff> findAll = buyOffDao.findAll(specification(BuyOff.CONFIRMRECEIPT,waybillNumber,ExpressMailOrderStatus.TO_COMPLETE_THE_GOODS), pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }

    /**
     * 分页查询揽收列表
     *
     * @param pageBean
     * @return
     */
    public PageBean<BuyOff> findDeliveryList(PageBean<BuyOff> pageBean, String waybillNumber) {
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<BuyOff> findAll = buyOffDao.findAll(specification(BuyOff.CONFIRM_THE_DELIVERY,waybillNumber,null), pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }


    /**
     * 分页查询派送列表
     *
     * @param pageBean
     * @return
     */
    public PageBean<BuyOff> signForList(PageBean<BuyOff> pageBean, String waybillNumber) {
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<BuyOff> findAll = buyOffDao.findAll(specification(BuyOff.DESIGNATE_DISPATCHERS, waybillNumber,null), pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }


    /**
     * 查询条件
     * @param status
     * @param waybillNumber
     * @return
     */
    private Specification<BuyOff>  specification(Integer status,String waybillNumber,Integer orderStatus){
        User loginedUser = SessionUtil.getLoginedUser();
        Specification<BuyOff> specification = (Specification<BuyOff>) (root, criteriaQuery, criteriaBuilder) -> {

            Predicate predicate = criteriaBuilder.equal(root.get("buyOffUser"), loginedUser.getId());
            Predicate predicate1 = criteriaBuilder.equal(root.get("status"), status);
            Predicate predicate2 = criteriaBuilder.equal(root.get("operation"), ProcessRecords.NO_OPERATIONS);

            predicate = criteriaBuilder.and(predicate, predicate1,predicate2);

            if (!StringUtils.isEmpty(waybillNumber)) {
                Predicate waybillNumberLike = criteriaBuilder.like(root.get("buyOffExpressMailOrder").get("waybillNumber"), "%" + waybillNumber + "%");
                predicate = criteriaBuilder.and(predicate, waybillNumberLike);
            }

            if (null != orderStatus){
                Predicate waybillNumberLike = criteriaBuilder.equal(root.get("buyOffExpressMailOrder").get("orderStatus"), orderStatus);
                predicate = criteriaBuilder.and(predicate, waybillNumberLike);
            }

            return predicate;
        };
        return specification;
    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public BuyOff find(Long id) {
        return buyOffDao.find(id);
    }

    /**
     * 保存编辑
     *
     * @param buyOff
     * @return
     */
    public BuyOff save(BuyOff buyOff) {
        return buyOffDao.save(buyOff);
    }

    /**
     * 签收完成
     *
     * @param id
     * @return
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRES_NEW, timeout = 20)
    public Integer signForComplete(Long id) {
        Integer abnormalJudgment = 0;
        try {
            BuyOff buyOff = buyOffDao.find(id);
            BuyOff newBuyOff = new BuyOff();
            buyOff.setOperation(ProcessRecords.HAVE_HANDLED);
            newBuyOff.setBuyOffExpressMailOrder(buyOff.getBuyOffExpressMailOrder());
            newBuyOff.setStatus(BuyOff.SEND_COMPLETE);
            newBuyOff.setBuyOffUser(buyOff.getBuyOffUser());
            buyOffDao.save(newBuyOff);
            buyOffDao.save(buyOff);
            ExpressMailOrder buyOffExpressMailOrder = buyOff.getBuyOffExpressMailOrder();
            buyOffExpressMailOrder.setOrderStatus(ExpressMailOrderStatus.SIGNFOR);
            ExpressMailOrder save = expressMailOrderDao.save(buyOffExpressMailOrder);
            SendEmailUtil sendEmailUtil = new SendEmailUtil();
            sendEmailUtil.setSourceEmail(sourceEmail);  //设置发件人
            //sendEmailUtil.setEmail(buyoffExpressMailOrder.getSenderEmail()); //设置收件人
            sendEmailUtil.setEmail(buyOffExpressMailOrder.getSenderEmail()); //设置收件人
            sendEmailUtil.setCode(authorizationCode); //设置授权码
            sendEmailUtil.sendMsg("快递签收提醒","您的订单编号"+ save.getWaybillNumber()+"已被签收"); //发送消息
        } catch (Exception e) {
            abnormalJudgment = 1;
        }
        return abnormalJudgment;
    }

    /**
     * 根据订单id查询
     * @param expressMailOrderId
     * @return
     */
    public List<BuyOff> findByBuyOffExpressMailOrder_IdOrderByCreateTime(Long expressMailOrderId){

        return buyOffDao.findByBuyOffExpressMailOrder_IdOrderByCreateTime(expressMailOrderId);
    }


}
